package com.loeng.module.infra.service.demo.demo02;

import com.loeng.framework.common.pojo.PageResult;
import com.loeng.framework.common.util.object.BeanUtils;
import com.loeng.module.infra.controller.admin.demo.demo02.vo.Demo02CategoryPageReqVO;
import com.loeng.module.infra.controller.admin.demo.demo02.vo.Demo02CategorySaveReqVO;
import com.loeng.module.infra.dal.dataobject.demo.demo02.Demo02CategoryDO;
import com.loeng.module.infra.dal.mysql.demo.demo02.Demo02CategoryMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static com.loeng.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.loeng.module.system.enums.ErrorCodeConstants.DEMO02_CATEGORY_NOT_EXISTS;

/**
 * 示例分类 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class Demo02CategoryServiceImpl implements Demo02CategoryService {

    @Resource
    private Demo02CategoryMapper demo02CategoryMapper;

    @Override
    public Long createDemo02Category(Demo02CategorySaveReqVO createReqVO) {
        // 插入
        Demo02CategoryDO demo02Category = BeanUtils.toBean(createReqVO, Demo02CategoryDO.class);
        demo02CategoryMapper.insert(demo02Category);
        // 返回
        return demo02Category.getId();
    }

    @Override
    public void updateDemo02Category(Demo02CategorySaveReqVO updateReqVO) {
        // 校验存在
        validateDemo02CategoryExists(updateReqVO.getId());
        // 更新
        Demo02CategoryDO updateObj = BeanUtils.toBean(updateReqVO, Demo02CategoryDO.class);
        demo02CategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteDemo02Category(Long id) {
        // 校验存在
        validateDemo02CategoryExists(id);
        // 删除
        demo02CategoryMapper.deleteById(id);
    }

    private void validateDemo02CategoryExists(Long id) {
        if (demo02CategoryMapper.selectById(id) == null) {
            throw exception(DEMO02_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public Demo02CategoryDO getDemo02Category(Long id) {
        return demo02CategoryMapper.selectById(id);
    }

    @Override
    public PageResult<Demo02CategoryDO> getDemo02CategoryPage(Demo02CategoryPageReqVO pageReqVO) {
        return demo02CategoryMapper.selectPage(pageReqVO);
    }

}